package com.nantian.logic.utils;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.UUID;

public class FileUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);


    /**
     * 单个文件上传
     * @param file
     * @param filePath
     * @return
     */
    public static String uploadFile( MultipartFile file,String filePath) {

        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String complete = fileName.substring(0,1);
        logger.info("上传的后缀名为：" + suffixName);

        logger.info("截取后的不带后缀的文件名为：" + complete);
        // 文件上传后的路径
//        String filePath = "E://test//";
        // 解决中文问题，liunx下中文路径，图片显示问题

        fileName = UUID.randomUUID() +","+complete+suffixName;

        String fileName1 = fileName;
        logger.info("更改后的文件名为："+fileName1);

        File file1 = new File(System.getProperty("user.dir"));
        // get parent dir
        String parentPath = file1.getParent();
        String path = "uploadImg" + File.separator + filePath + File.separator + fileName;
        System.out.println("图片保存目录地址"+path);

        String absolutePath = parentPath + File.separator+path;
        File dest = new File(absolutePath);
        // 检测是否存在目录
        if (!dest.getParentFile().getParentFile().exists()) {
            dest.getParentFile().getParentFile().mkdirs();
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
        }
        try {
            file.transferTo(dest);
            return path;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }


    /**
     * 用于接收上传文件与数据
     * @param file
     * @param filePath
     * @return
     */
    public static String uploadFileAndData( MultipartFile file,String filePath) {

        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        logger.info("上传的后缀名为：" + suffixName);


        String complete = fileName.substring(0,fileName.lastIndexOf("."));
        logger.info("截取后的不带后缀的文件名为(即文件前缀)：" + complete);
        // 文件上传后的路径
//        String filePath = "E://test//";
        // 解决中文问题，liunx下中文路径，图片显示问题

        fileName = UUID.randomUUID() +","+complete+suffixName;

        String fileName1 = fileName;
        logger.info("更改后的文件名为："+fileName1);
        String absolutePath = filePath+fileName1;
        File dest = new File(absolutePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return absolutePath;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }







    /**
     * 文件批量上传
     * @param request
     * @return
     */
    public static String fileBatchUpload(HttpServletRequest request){
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        return "upload successful";
    }


    /**
     * 单张图片输出流
     * @param file
     * @param info
     */

    public static void outputFileStream(File file, String info,String path,HttpServletResponse response){
        try{

            FileInputStream inputStream = new FileInputStream(file);
            BufferedImage image = ImageIO.read(inputStream);

            String[] temp = path.split("\\.");
            System.out.println(temp.length);
            response.setContentType("image/" + temp[temp.length - 1]);
            System.out.println("格式:" + temp[temp.length - 1]);
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        }catch (IOException e){
            logger.info(info);
        }
    }



    }
